package FlowGram.Application.Parser.Actions;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import FlowGram.Application.Parser.FinchParserException;
import FlowGram.Application.Parser.Controllers.FinchController;


/**
 * 
 * @author thackray
 *
 */
public class Chirp extends FinchAction {

	
	protected int frequency;
	protected int duration;
	
	
	public int getFrequency(){
		return this.frequency;
	}
	public void setFrequency(int freq){
		this.frequency = freq;
	}
	public void setDuration(int duration){
		this.duration = duration;
	}
	public int getDuration(){
		return this.duration;
	}
	
	
	public static boolean matches(String s){
		return s.matches("^chirp\\s+.*");
	}
	public static String syntax(){
		return "chirp <frequency> <duration>";
	}
	
	@Override
	public String toCode(int indent) {
		return "chirp "+this.frequency+" "+(((double)this.duration)/1000);
	}
	@Override
	public String toHTML(String idPrefix){
		return this.toCode();
	}
	@Override
	public void execute(FinchController controller) {
		if(this.frequency > 0){
			controller.chirp(this.frequency, this.duration);
		}
		try {
			Thread.sleep(this.duration);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	}

	@Override
	public String logMessage() {
		return "chirping at "+this.frequency+" Hz for "+(((double)this.duration)/1000)+" seconds";
	}

	@Override
	public void parse(String statement) throws FinchParserException {
		Pattern p = Pattern.compile("^chirp\\s+(\\d+|nothing)\\s+([\\d\\.]+)");
		Matcher matcher = p.matcher(statement);
		while(matcher.find()){
			if(matcher.group(1) != null){
				if(matcher.group(1).equals("nothing")){
					this.frequency = -1;
				}else{
					this.frequency = Integer.parseInt(matcher.group(1));
				}
				if(matcher.group(2) != null){
					this.duration = (int)(Double.parseDouble(matcher.group(2))*1000);;
				}else{
					throw new FinchParserException("Chirp needs a duration!");
				}
			}else{
				throw new FinchParserException("Chirp needs a frequency!");
			}
		}
	}

}
